package com.lvcoding.cloud.user.conroller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Description 七牛云测试
 * @Date 2020-07-29 6:18 下午
 * @Author wuyanshen
 */
@Controller
@RequestMapping("qiniu")
public class QiNiuController {

    @GetMapping("qiniu/{key}")
    public void getImage(@PathVariable("key") String key, HttpServletResponse response) throws IOException {
        String accessKey = "-ZO7n2CEHsomMqi63ilMvkRcBJUNFl7BOP4IbFo0";
        String secretKey = "F7FwR21pixI6zayJ11wnDL4HBZlq9uAajruJJKtr";
        String bucket = "wys-huanan";
        String domain = "http://qdrjzu6xq.bkt.clouddn.com/";
        String prefix = "";

        //Configuration config = new Configuration(Region.huanan());
        //Auth auth = Auth.create(accessKey, secretKey);
        //BucketManager bucketManager = new BucketManager(auth, config);
        ////列举空间文件列表
        //BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(bucket, prefix);
        //FileInfo[] fileInfos = fileListIterator.next();
        //
        //Random rand = new Random();
        //int index = rand.nextInt(fileInfos.length);
        //FileInfo fileInfo = fileInfos[index];
        //System.out.println("output:>>>" + fileInfo.key);

        BufferedImage oriImage = ImageIO.read(getImageStream(domain+key));
        ImageIO.write(oriImage,"jpg", response.getOutputStream());
    }

    /**
     * 获取网络图片流
     *
     * @param url
     * @return
     */
    private InputStream getImageStream(String url) {
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);
            connection.setRequestMethod("GET");
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                return inputStream;
            }
        } catch (IOException e) {
            System.out.println("获取网络图片出现异常，图片路径为：" + url);
            e.printStackTrace();
        }
        return null;
    }
}
